from django.utils.deprecation import MiddlewareMixin
from django.conf import settings
from web import models
from django.shortcuts import redirect
import datetime

class Tracer(object):
    def __init__(self):
        self.user=None
        self.project=None
        self.price_policy=None

class AuthMiddleware(MiddlewareMixin):

    def process_request(self,request):
        request.tracer=Tracer()
        user_id=request.session.get('user_info',0)
        user_obj=models.UserInfo.objects.filter(pk=user_id).first()
        request.tracer.user=user_obj
        #检查用户访问的白名单 通过的话返回空
        if request.path_info in settings.WHITE_REGEX_URL_LIST:
            return
        #用户没有登录的话  重定向到登录页面
        if not request.tracer.user:
            return redirect('web:login_user_pwd')

        #获取用户最大id的交易记录 订单是支付状态
        _object=models.Transaction.objects.filter(user=user_obj,status=2).order_by('-id').first()
        #获取当前时间 和 交易记录中的 订单结束时间
        now=datetime.datetime.now()
        if _object and _object.end_datetime and _object.end_datetime<now:
            _object=models.Transaction.objects.filter(user=user_obj,status=2,price_policy__category=1).first()
        request.tracer.price_policy=_object.price_policy

    def process_view(self,request,view,args,kwargs):
        #如果不是以/manage/  开头的  放行
        if not request.path_info.startswith('/manage/'):
            return
        project_id=kwargs.get('project_id')
        project_obj=models.Project.objects.filter(pk=project_id,creator=request.tracer.user).first()
        #是否时我创建的项目
        if project_obj:
            request.tracer.project=project_obj
            return
        project_join_obj=models.ProjectUser.objects.filter(project_id=project_id,user=request.tracer.user).first()
        #是否是我参与的项目
        if project_join_obj:
            request.tracer.project=project_join_obj.project
            return
        return redirect('web:project_list')